package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.CourseConstants;
import cn.itsource.ymcc.constant.OrderConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.mapper.PayOrderMapper;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.node.POJONode;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RocketMQMessageListener(consumerGroup = "service-order-transaction-consumer",
        //Topic
        topic = OrderConstants.MQ_TOPIC_COURSEORDER_PAYORDER,
         //TAGS
        selectorExpression = OrderConstants.MQ_TAGS_COURSEORDER_PAYORDER
)
@Slf4j
public class OrderMQConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Override
    public void onMessage(MessageExt message) {

        try {
            byte[] body = message.getBody();
            String bodyStr = new String(body, Constants.UTF8);
            CourseOrder courseOrder = JSON.parseObject(bodyStr, CourseOrder.class);

            //生成支付单并保存
            PayOrder payOrder = new PayOrder();
            payOrder.setCreateTime(new Date());
            payOrder.setOrderNo(courseOrder.getOrderNo());
            payOrder.setAmount(courseOrder.getPayAmount());
            payOrder.setPayType(courseOrder.getPayType());
            List<CourseOrderItem> itemList = courseOrder.getItemList();
            String collect = itemList.stream().map(item -> item.getCourseId().toString()).collect(Collectors.joining(","));
            payOrder.setRelationId(collect);
            payOrder.setUserId(courseOrder.getUserId());
            payOrder.setSubject(courseOrder.getTitle());
            payOrder.setPayStatus(RConst.Num.INT_0);
            payOrderMapper.insert(payOrder);
            System.out.println("支付单生成成功");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("站内推送失败");
        }
    }
}